import {RequestMethod} from "../lib/defines";
import { MemberBase, MemberOption, RoomBase } from "../utils/types";
import {isType} from "../utils/utils";

type optionType = {
  owner?: MemberOption
  rooms?: RoomBase[]
  members?: MemberBase[]
}

export default function login (app) {
  const { socket, rooms: lRooms } = app.locals;
  const { classId, userId, username } = socket.handshake.query;

  /**
   * 用户上线后 - 登录
   *
   * 如果用户上线时，传入了 classId 则，默认为用户 创建/加入 常驻房间
   *
   * TODO 用于 创建/加入 常驻房间
   * @params classId 常驻房间 ID
   * @params classname 常驻房间 ID
   */
  socket.on(RequestMethod.login, function({ rooms, members }: optionType, cb) {
    const owner = { userId, username }
    const room = lRooms[classId]
    const __members = []

    if (isType(rooms, 'array')) {
      (rooms as RoomBase[]).forEach(({ classId }) => {
        if (lRooms[classId]) {
          lRooms[classId].getMembers().forEach(__members.push)

          // 通知当前房间的其他人，但是自己并不收到消息
          socket.broadcast.to(classId).emit('online', owner as any);
        }
      });
    }

    if (isType(members, 'array')) {
      (members as MemberBase[]).forEach(({ userId }) => {
        const member = room.members[userId]
        if (member) {
          __members.push(member as never)
          socket.to(member.socketId).emit('online', owner as any);
        }
      });
    }

    // 回调
    if (cb) {
      cb({
        status: 'ok',
        resolve: 'logged',
        members: __members
      })
    }
  });
}
